package com.xujianlong.day07;

import com.xujianlong.bean.LoginEvent;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.elasticsearch.search.aggregations.metrics.ParsedSingleValueNumericMetricsAggregation;

import java.time.Duration;

public class Flink05_Project_Login {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> dataStreamSource = env.readTextFile("input/LoginLog.csv");
        SingleOutputStreamOperator<LoginEvent> watermarks = dataStreamSource.map(new MapFunction<String, LoginEvent>() {
            @Override
            public LoginEvent map(String s) throws Exception {
                String[] split = s.split(",");
                return new LoginEvent(
                        Long.parseLong(split[0]),
                        split[1],
                        split[2],
                        Long.parseLong(split[3])
                );
            }
        }).assignTimestampsAndWatermarks(WatermarkStrategy
                .<LoginEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner(new SerializableTimestampAssigner<LoginEvent>() {
                    @Override
                    public long extractTimestamp(LoginEvent loginEvent, long l) {
                        return loginEvent.getEventTime() * 1000;
                    }
                })
        );

        KeyedStream<LoginEvent, Long> keyedStream = watermarks.keyBy(new KeySelector<LoginEvent, Long>() {
            @Override
            public Long getKey(LoginEvent loginEvent) throws Exception {
                return loginEvent.getUserId();
            }
        });
        SingleOutputStreamOperator<String> process = keyedStream.process(new KeyedProcessFunction<Long, LoginEvent, String>() {
            private ValueState<Long> fail_timer;
            private final Long interval = 2L;

            @Override
            public void open(Configuration parameters) throws Exception {
                fail_timer = getRuntimeContext().getState(new ValueStateDescriptor<Long>("fail_timer", Long.class));
                //System.out.println(fail_timer.value());
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                //计时器时间到了，表示两秒内仅登录失败过一次
                ctx.timerService().deleteProcessingTimeTimer(fail_timer.value());
                fail_timer.clear();
            }

            @Override
            public void processElement(LoginEvent value, Context ctx, Collector<String> out) throws Exception {
                if ("fail".equals(value.getEventType())) {
                    long curTime = ctx.timerService().currentProcessingTime();
                    //如果timer非空则之前有过登录失败了
                    if (fail_timer.value() != null) {
                        //在这里表示已经连续失败至少两次了
                        out.collect(value.getUserId()+"连续两次失败了");

                        //计时器从最新数据开始计时
                        ctx.timerService().deleteProcessingTimeTimer(fail_timer.value());
                        fail_timer.update(curTime + interval);
                        ctx.timerService().registerProcessingTimeTimer(fail_timer.value());
                    } else {
                        //表示第一次失败，开启登录失败计时器
                        fail_timer.update(curTime + interval);
                        ctx.timerService().registerProcessingTimeTimer(fail_timer.value());
                        //out.collect("第一次失败");
                    }
                } else {
                    //表示登录成功过,如果登录失败过则清空计时器
                    if (fail_timer.value() != null) {
                        //System.out.println(fail_timer.value());
                        ctx.timerService().deleteProcessingTimeTimer(fail_timer.value());
                        fail_timer.clear();
                        //out.collect("登录成功,清空计时器");
                    }else{
                        //out.collect("登录成功");
                    }
                }
            }
        });
        process.print();

        env.execute();
    }
}
